# -*- coding:utf-8 -*-

from datetime import datetime, timedelta
import time
import calendar

def get_timestamp():
    """
    获取当前日期的时间戳
    :return:
    """
    return int(time.time())


def get_datetime():
    """
    获取当前系统时间
    :return:
    """
    today_date = datetime.today().strftime("%Y-%m-%d %H:%M:%S")
    return today_date


def get_current_timestamp():
    """
    获取当前日期的时间戳
    :return:
    """
    return int(time.time())


def get_current_datetime():
    """
    获取当前系统时间
    :return:
    """
    today_date = datetime.today().strftime("%Y-%m-%d %H:%M:%S")
    return today_date


def get_current_date():
    """
    获取当前系统时间(截取到年月日)
    :return:
    """
    today_date = datetime.today().strftime("%Y-%m-%d")
    return today_date


def get_date_time_of_before_day(n, label=0):
    """
    获取以当天为基准的N天前开始或结束的时间字符串
    :param n:
    :param label: 0 :当天开始时间字符串，1：当天结束时间字符串
    :return:
    """
    nowdt = datetime.now()
    d = timedelta(days=n)
    if label == 1:
        return str((nowdt-d).strftime("%Y-%m-%d 23:59:59"))
    else:
        return str((nowdt-d).strftime("%Y-%m-%d 00:00:00"))


def get_timestamp_of_before_day(n, label):
    """
    获取某天开始与结束的时间戳
    :param n:
    :param label: 0 :当天开始时间戳，1：当天结束时间戳
    :return:
    """
    nowdt = datetime.now()
    d = timedelta(days=n)
    if label == 1:
        return convert_date_to_timestamp(str((nowdt-d).strftime("%Y-%m-%d 23:59:59")))
    else:
        return convert_date_to_timestamp(str((nowdt-d).strftime("%Y-%m-%d 00:00:00")))


def convert_date_to_timestamp(t):
    """
    日期转换为时间戳
    :param t:
    :return:
    """
    t = time.strptime(t, "%Y-%m-%d %H:%M:%S")
    d = datetime(t[0], t[1], t[2], t[3], t[4], t[5])
    result = int(time.mktime(d.timetuple()))
    return result


def convert_timestamp_to_date(time_stamp):
    """
    时间戳转换为可读日期
    :param time_stamp:
    :return:
    """
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time_stamp)))
    return timestamp


def get_differ_days(str_datetime):
    """
    计算指定日期与当前日期时间差
    :param str_datetime:查询的字符串:2015-05-20 12:00:00
    :return:
    """
    now_dt = datetime.today()
    old_dt = datetime.strptime(str_datetime, '%Y-%m-%d %X')
    days = (now_dt-old_dt).days
    return days


def get_before_or_after_date(num, label, *s):
    """
    获取前几天或后几天的日期,试用下单用，试用期为7天
    label:0,前几天
    label:1,后几天
    例如：2016-12-15 7天后是2016-12-22
    :param num: 天数
    :param label: 向前或向后标识
    :param *s: 默认当前日期为基准日期，如果第三个参数存在则以传入的日期为基准日期
    :return:
    """
    if s:
        nowdt = datetime.strptime(s[0], '%Y-%m-%d')
    else:
        nowdt = datetime.now()
    d = timedelta(days=num)
    if label == 0:
        d = -d
    return (nowdt+d).strftime('%Y-%m-%d')


def get_today_month(n=0):
    """
    获取当前日期前后N月的日期
    if n>0, 获取当前日期前N月的日期
    if n<0, 获取当前日期后N月的日期
    date format = "YYYY-MM-DD"
    """
    day = time.strftime("%d", time.localtime())
    year = time.strftime("%Y", time.localtime())
    mon = time.strftime("%m", time.localtime())
    # year=2014
    # mon=12
    # day=1
    (y, m, d) = getyearandmonth(year, mon, n)
    arr = (y, m, d)
    if int(day) < int(d):
        arr = (y, m, day)
    return "-".join("%s" % i for i in arr)


def getyearandmonth(year, mon, n=0):
    """
    get the year,month,days from today
    befor or after n months
    """

    thisyear = int(year)
    thismon = int(mon)
    totalmon = thismon + n
    if n >= 0:
        if totalmon <= 12:
            days = str(get_days_of_month(thisyear, totalmon))
            totalmon = addzero(totalmon)
            return year, totalmon, days
        else:
            i = totalmon / 12
            j = totalmon % 12
            if j == 0:
                i -= 1
                j = 12
            thisyear += i
            days = str(get_days_of_month(thisyear, j))
            j = addzero(j)
            return str(thisyear), str(j), days
    else:
        if (totalmon > 0) and (totalmon < 12):
            days = str(get_days_of_month(thisyear, totalmon))
            totalmon = addzero(totalmon)
            return year, totalmon, days
        else:
            i = totalmon / 12
            j = totalmon % 12
            if j == 0:
                i -= 1
                j = 12
            thisyear += i
            days = str(get_days_of_month(thisyear, j))
            j = addzero(j)
            return str(thisyear), str(j), days


def get_days_of_month(year, mon):
    """
    get days of month
    """
    return calendar.monthrange(year, mon)[1]


def addzero(n):
    """
    add 0 before 0-9
    return 01-09
    """
    nabs = abs(int(n))
    if nabs < 10:
        return "0" + str(nabs)
    else:
        return nabs


def get_end_date(n):
    """
    获取预付单有效结束日期
    :param n:
    :return:
    """
    n = int(n)
    #购物车
    if n == 1:
        months = 13
    elif n == 2:
        months = 26
    else:
        months = n*12+3
    #获取n月后日期
    end_date = get_today_month(n=months)
    #计算n月后日期的前一天日期
    return get_before_or_after_date(1, 0, end_date)


def change_date_formal(t, date_format='%Y-%m-%d'):
    """
    转化为前端显示用日期格式
    :param t: 固定日期格式的字符串（如'2016-01-02'）
    :param date_format：需要转化成的日期格式
    :return:
    """
    t = time.strptime(t, "%Y-%m-%d")
    d = datetime(t[0], t[1], t[2], t[3], t[4], t[5])
    result = int(time.mktime(d.timetuple()))
    timestamp = time.strftime(date_format,  time.localtime(int(result)))
    return timestamp


def get_date_list(n=7):
    """
    获取指定范围的日期集合
    :param n: n:几天这内,默认为7天
    :return:日期列表
    """

    date_list = []
    for i in range(n):
        date_list.append((datetime.now()-timedelta(days=i)).strftime("%Y-%m-%d"))
    return date_list
